/**
 * @description CommentManager
 */
import { useQuasar } from '@teld/q-components';
import {
  computed,
  ref,
  defineComponent,
  defineAsyncComponent,
  provide,
  reactive,
} from 'vue';

import {
  getUserInfoFromSession,
  getUserProfiles,
  saveUserStringProfile,
  getSysLoginUser,
} from '../comment/hooks/api';
import {
  INPUT_WORD_LIMIT,
  ATTACHMENT_MAX_SIZE,
  ATTACHMENT_MAX_SIZE_KEY,
  RECENTLY_MENTIONED_USERS_KEY,
} from '../comment/utils';
import { RECENTLY_MENTIONED_USERS_LIMIT } from '../comment/utils/constants.js';
export default defineComponent({
  name: 'CommentManager',
  components: {},
  props: {
    allComments: Array,
    enableComment: Boolean,
    enableBottomComment: Boolean,
  },
  emits: [],
  setup(props, { emit }) {
    const teldCommentRef = ref();
    const commentScrollAreaRef = ref();
    const isComment = ref(false);
    const DraftEditorRef = ref(null);
    const DraftEditor = defineAsyncComponent(
      () => import('../comment/pc/draft-editor/index.vue'),
    );
    provide('qLangComment', {
      funcImageUploadFailed: () => {},
      funcAttachmentLimit:() => {},
    });
    const $q = useQuasar();
    const recentlyMentionedUsers = ref([]);
    const loginUserInfo = reactive({
      // avatar: 'Avatar || headImg',
      // userId: 'UserId',
      // userName: 'UserName',
    });
    // 快捷选人popup定位用的外部容器，用于计算出现在@符号的上下左右位置
    provide('getContainerForPersonnelSelectorPopup', isComment => {
      return teldCommentRef.value;
    });
    provide('dense', props.dense);
    // provide('emptyText', props.emptyText);
    provide('loginUserInfo', loginUserInfo);
    provide('sendButtonText', $q.lang.comment.confirmation);
    provide('inputMaxLength', '1000000');
    provide('notificationLink', () => {
      // 如果关闭了通知
      if (disableNotifications.value) return '';
      // ----开启通知的情况--
      const trimmedUrl =
        notificationLink.value && notificationLink.value.trim();
      return trimmedUrl || location.href;
    });
    // provide('pageUrl', () => {
    //   // 如果关闭了通知
    //   if (disableNotifications.value) return '';
    //   // ----开启通知的情况--
    //   // 1. 页面在web框架中
    //   if (isInWebFramework.value) {
    //     // web 框架中时需要子应用的url，否则通知链接无法进入该子应用的页面
    //     return fasUrl.value && fasUrl.value.trim()
    //       ? fasUrl.value.trim()
    //       : '';
    //   }
    //   // 2. 页面独立打开，不需要这个用于web框架的fpath参数
    //   return '';
    // });
    provide('getAttachmentMaxSize', () => {
      // TODO
      return attachmentMaxSize;
    });
    provide('recentlyMentionedUsers', recentlyMentionedUsers);
    provide('updateRecentlyMentionedUsers', item => {
      const items = Array.isArray(item) ? item : [item];
      // 去重，顶部push压栈，更新当前变量，更新到数据库
      const newList = [
        ...items,
        ...recentlyMentionedUsers.value.filter(
          n => !items.some(o => o.UserID === n.UserID),
        ),
      ].slice(0, RECENTLY_MENTIONED_USERS_LIMIT);
      recentlyMentionedUsers.value = newList;
      saveUserStringProfile(recentlyMentionedUsers.value);
    });
    provide('emitEvent', (code = 'comment', data = null) => {
      emit(code, data);
    });
    async function getUserProfileInfo() {
      try {
        const data = await getUserProfiles();

        if (!data || data.state !== '1') {
          return;
        }
        const _data_ = data.data;
        attachmentMaxSize.value =
          _data_[ATTACHMENT_MAX_SIZE_KEY] || ATTACHMENT_MAX_SIZE;
        recentlyMentionedUsers.value = JSON.parse(
          _data_[RECENTLY_MENTIONED_USERS_KEY] || '[]',
        );
        console.log(
          `UserProfile${ATTACHMENT_MAX_SIZE_KEY}=${attachmentMaxSize.value}`,
        );
        // TODO mock
        // if (!this.recentlyMentionedUsers.length) {
        //   this.recentlyMentionedUsers = mockUserList;
        // }
      } catch (error) {
        console.log(error);
      }
    }

    const { allComments } = props;
    const zipComment = (commentList, isdelete, reference) => {
      if (!commentList) return [];
      let list = [];
      commentList.forEach(element => {
        if (isdelete) {
          element.isDelete = isdelete;
        }
        if (reference) {
          element.reference = reference;
        }
        if (element.children) {
          let zipList = zipComment(
            element.children,
            element.isDelete,
            element.reference,
          );
          list = list.concat(zipList);
          delete element.children;
        }
        list.push(element);
      });
      return list;
    };
    const computedCommentNumsByType = computed(() => {
      let allTags = zipComment(_.cloneDeep(allComments.value));

      return {
        all: allTags.filter(item => !item.isDelete).length,
        comment: allTags.filter(item => item.reference && !item.isDelete)
          .length,
        articlComment: allTags.filter(item => !item.reference && !item.isDelete)
          .length,
      };
    });
    const type = ref('all');
    const computedCommentByType = computed(() => {
      return {
        all: allComments.value.filter(item => !item.isDelete),
        comment: allComments.value.filter(
          item => item.reference && !item.isDelete,
        ),
        articlComment: allComments.value.filter(
          item => !item.reference && !item.isDelete,
        ),
      }[type.value];
    });
    const generateReference = (reference, id) => {
      return (
        <span
          onClick={() => {
            let target = document.querySelectorAll(`span[class*="${id}"]`);
            if (!target || !target.length) {
              return Funcs.Notify('', $q.lang.editorV2.refrenceIsDelete, 'warning');
            }
            target[0].scrollIntoView({ block: 'center' });
          }}
          class={'reference'}
          title={$q.lang.editorV2.positionToOrgin}
        >
          {$q.lang.editorV2.refrence}：{reference}
        </span>
      );
    };
    const getDifferDays = date => {
      let diffHour = Funcs.DiffHours(date, new Date());
      if (diffHour < 24 && diffHour > 0) {
        return diffHour + $q.lang.editorV2.beforeHour;
      }
      if (diffHour == 0) {
        let diffmin = Funcs.DiffMinutes(date, new Date());
        if (diffmin == 0) {
          return Funcs.DiffSeconds(date, new Date()) +  $q.lang.editorV2.beforeSecond;
        }
        return diffmin +  $q.lang.editorV2.beforeMinute;
      }
      let diffdays = Funcs.DiffDays(date, new Date());
      return diffdays +  $q.lang.editorV2.beforeDay;
    };
    const generateComment = (target, pContent) => {
      let Template = [];
      if (!target.isDelete) {
        Template.push(
          <div
          class={"comment_bottom"}
            style={`margin-top:8px;${pContent && target.pid ? 'margin-left:38px' : ''}`}
          >
            <p class={'avatarParent'}>
              <span class={'avatar'} style={'height:40px'}>
                {(() => {
                  if (target.avatar) {
                    return <img style={'height:40px'} src={target.avatar} />;
                  } else {
                    return (
                      <svg
                        style={'height:40px'}
                        xmlns='http://www.w3.org/2000/svg'
                        viewBox='0 0 24 24'
                        fill='currentColor'
                      >
                        <path d='M20 22H4V20C4 17.2386 6.23858 15 9 15H15C17.7614 15 20 17.2386 20 20V22ZM12 13C8.68629 13 6 10.3137 6 7C6 3.68629 8.68629 1 12 1C15.3137 1 18 3.68629 18 7C18 10.3137 15.3137 13 12 13Z'></path>
                      </svg>
                    );
                  }
                })()}
              </span>
              <span>
                <i class={'username'}>{target.account}</i>

                <i class={'difftime'}>{getDifferDays(target.createdAt)}</i>
              </span>
              <span
                class={'operate'}
                style={`
    gap: 8px;`}
              >
                {(() => {
                  return (
                    <i
                      onClick={() => {
                        let Template = `<span pid='${target.pid || target.id}' reference='${target.reference}' >回复 </span><span data-user-id="$userid" class="teld-comment--mentioned-user" contenteditable="false" style="display: inline-block; padding-right: 4px;">@$userName ：</span>`;
                        Template = Template.replace(
                          /\$userName/gi,
                          target.account,
                        );
                        DraftEditorRef.value.$el.querySelector(
                          '.draft-editor--input',
                        ).innerHTML = Template;
                      }}
                      class={'fas dx-icon icon-t-comment-fine'}
                    ></i>
                  );
                })()}
                {(()=>{
                    if(target.account==window.Session?.UserName){
                        return <i
                        class={'fas dx-icon icon-t-delete-outlined'}
                        onClick={() => {
                          emit('deleteComment', target);
                        }}
                      ></i>
                    }
                })()}

              </span>
            </p>
            {(() => {
              if (target.pid && pContent) {
                return (
                  <span
                    v-html={decodeURIComponent(pContent)}
                    style={`margin-left: 38px;padding-left:6px;border-left:2px solid ${target.mainColor};font-size:14px;color:rgba(0,0,0,.56)`}
                  ></span>
                );
              }
            })()}
            <p
              class={'commentCotentBox'}
              style={`    display: flex;
    align-items: center;
    gap: 8px;`}
            >
              <span
                class={'commentContetn'}
                v-html={decodeURIComponent(target.content)}
              ></span>

            </p>
          </div>,
        );
        if (target.children) {
          target.children.forEach(item => {
            Template = Template.concat(generateComment(item, target.content));
          });
        }
      }
      return Template;
    };
    const render = () => {
      return (
        <div class={'CommentManager'} ref={teldCommentRef}>

          <header>
            <span
              class={type.value == 'all' ? 'checked' : ''}
              onClick={() => {
                type.value = 'all';
              }}
            >
              {$q.lang.editorV2.allComment}
              {computedCommentNumsByType.value.all
                ? `(${computedCommentNumsByType.value.all})`
                : ''}
            </span>
            <span
              class={type.value == 'articlComment' ? 'checked' : ''}
              onClick={() => {
                type.value = 'articlComment';
              }}
            >
              {$q.lang.editorV2.currentComment}
              {computedCommentNumsByType.value.articlComment
                ? `(${computedCommentNumsByType.value.articlComment})`
                : ''}
            </span>
            <span
              class={type.value == 'comment' ? 'checked' : ''}
              onClick={() => {
                type.value = 'comment';
              }}
            >
              {$q.lang.editorV2.comment}
              {computedCommentNumsByType.value.comment
                ? `(${computedCommentNumsByType.value.comment})`
                : ''}
            </span>
          </header>
          <div class={'CommentManagerContent'}>
            {(() => {
              let Template = [];
              for (let i in computedCommentByType.value) {
                let tm = (
                  <div
                    style={
                      computedCommentByType.value[i].reference
                        ? `border-left:2px solid ${computedCommentByType.value[i].mainColor}`
                        : ''
                    }
                  >
                    <p>
                      {(() => {
                        if (computedCommentByType.value[i].reference) {
                          return generateReference(
                            computedCommentByType.value[i].reference,
                            computedCommentByType.value[i].id,
                          );
                        }
                      })()}
                    </p>
                    {generateComment(computedCommentByType.value[i])}
                  </div>
                );
                if (!computedCommentByType.value[i].isDelete) {
                  Template.push(tm);
                }
              }
              return Template;
            })()}
            {/* <span v-html={computedCommentByType.value}></span> */}
          </div>
          {(() => {
            if (props.enableComment && props.enableBottomComment) {
              return (
                <DraftEditor
                  ref={DraftEditorRef}
                  notAutoFocus={true}
                  isComment={isComment.value}
                  show-avatar={false}
                  is-comment={true}
                  visible={true}
                  offset-parent={
                    teldCommentRef.value && teldCommentRef.value.$el
                  }
                  auto-clear-on-hidding={true}
                  class='w-full py-3 border-t border-solid border-gray-200'
                  class="[dense ? 'px-3' : 'px-5']"
                  onComment={e => {
                    emit('addComment', e);
                  }}
                ></DraftEditor>
              );
            }
          })()}
        </div>
      );
    };
    return render;
  },
});
